from sort_API import get_overlap_rate
import numpy as np


def overlap_sort(sorted_data_kmeans, reading_sequence, overlap_threshold=0.65, base_y_threshold=50):
    """
    自适应版本：根据字符大小动态调整y轴范围阈值
    """
    sorted_data_overlap = []

    for cluster_idx, cluster_data in enumerate(sorted_data_kmeans):
        if not cluster_data:
            sorted_data_overlap.append([])
            continue

        print(f"处理第 {cluster_idx + 1} 个簇，共 {len(cluster_data)} 个字符")

        # 计算平均字符高度
        avg_char_height = np.mean([elem['y_end'] - elem['y_start'] for elem in cluster_data])
        # 动态调整y轴阈值（基于平均字符高度的倍数）
        dynamic_y_threshold = max(base_y_threshold, avg_char_height * 2)
        print(f"  平均字符高度: {avg_char_height:.1f}, 动态Y轴阈值: {dynamic_y_threshold:.1f}")

        used_flags = [False] * len(cluster_data)
        # 按y坐标排序（从上到下）
        cluster_data_sorted = sorted(cluster_data, key=lambda x: x['y_start'], reverse=True)
        cluster_columns = []

        for i in range(len(cluster_data_sorted)):
            if used_flags[i]:
                continue

            current_column = [cluster_data_sorted[i]]
            used_flags[i] = True

            # 记录当前列的y轴中心线
            current_y_centers = [(cluster_data_sorted[i]['y_start'] + cluster_data_sorted[i]['y_end']) / 2]

            # 查找相邻字符
            for j in range(len(cluster_data_sorted)):
                if used_flags[j] or i == j:
                    continue

                cur_elem = cluster_data_sorted[j]
                cur_y_center = (cur_elem['y_start'] + cur_elem['y_end']) / 2

                # 检查是否与当前列的某个字符在y轴相邻
                is_adjacent = False
                for existing_y_center in current_y_centers:
                    if abs(cur_y_center - existing_y_center) <= dynamic_y_threshold:
                        is_adjacent = True
                        break

                if not is_adjacent:
                    continue

                # 与当前列的所有字符计算最大重叠率
                max_overlap = 0
                for existing_elem in current_column:
                    start1, end1 = cur_elem['x_start'], cur_elem['x_end']
                    start2, end2 = existing_elem['x_start'], existing_elem['x_end']
                    overlap = get_overlap_rate(start1, end1, start2, end2)
                    max_overlap = max(max_overlap, overlap)

                if max_overlap >= overlap_threshold:
                    current_column.append(cur_elem)
                    used_flags[j] = True
                    current_y_centers.append(cur_y_center)

            # 按y坐标排序当前列
            current_column.sort(key=lambda x: x['y_start'])
            cluster_columns.append(current_column)

        # 按x坐标排序所有列
        reverse = True
        if reading_sequence == 0:
            reverse = False

        cluster_columns.sort(key=lambda column: np.mean([elem['x_start'] for elem in column]), reverse=reverse)
        sorted_data_overlap.append(cluster_columns)

        print(f"  簇 {cluster_idx + 1} 分成 {len(cluster_columns)} 列")

    return sorted_data_overlap
